package com.aa.base

import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import java.text.DecimalFormat

/**
 * @author Afra55
 * @date 2020/11/12
 * A smile is the best business card.
 * https://github.com/square/moshi
 */
object JsonUtil {
    val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()

}

fun Any.toJsonString(): String {
    try {
        val jsonAdapter = JsonUtil.moshi.adapter(javaClass)
        return jsonAdapter.toJson(this)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return ""
}

fun <T> String.toObject(clazz: Class<T>): T? {
    try {
        val jsonAdapter = JsonUtil.moshi.adapter(clazz)
        return jsonAdapter.fromJson(this)
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return null

}
fun  String.toMap(): Map<String, Any>? {
    try {

        val type = Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java)

        val jsonAdapter: JsonAdapter<Map<String, Any>>? = JsonUtil.moshi.adapter(type)
        return jsonAdapter?.fromJson(this)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

fun mapJson(vararg pair: Pair<String, Any?>): String? {
    try {
        val map = mapOf(*pair)
        return map.toJsonString()
    } catch (e: Exception) {
    }

    return null
}


fun Any?.toEasyString():String {
    try {
        if (this is Double) {
            val df = DecimalFormat("#")
            return df.format(this)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return this.toString()
}

fun Any?.toMoneyEasyString():String {
    try {
        if (this is Double) {
            val df = DecimalFormat("#.##")
            return df.format(this)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return this.toString()
}